package com.mmall.service.impl;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysAclMapper;
import com.mmall.dao.SysAclModuleMapper;
import com.mmall.exception.ParamException;
import com.mmall.param.AclModuleParam;
import com.mmall.pojo.SysAclModule;
import com.mmall.service.ISysAclModuleService;
import com.mmall.service.ISysLogService;
import com.mmall.util.BeanValidatorUtil;
import com.mmall.util.IpUtil;
import com.mmall.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author wangtengyu
 * @Create 2018-03-13-15:51
 */
@Service("iSysAclModuleService")
public class SysAclModuleServiceImpl implements ISysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;

    @Autowired
    private SysAclMapper sysAclMapper;


    @Autowired
    private ISysLogService iSysLogService;


    /**
     * 保存权限模块
     *
     * @param param
     */
    public void save(AclModuleParam param) {
        BeanValidatorUtil.check(param);
        if (checkExist(param.getParentId(), param.getName(), param.getId())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule sysAclModule = SysAclModule.builder().name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        sysAclModule.setLevel(LevelUtil.getLevel(getLevel(param.getParentId()), param.getParentId()));
        sysAclModule.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysAclModule.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysAclModule.setOperateTime(new Date());
        sysAclModuleMapper.insertSelective(sysAclModule);
        iSysLogService.saveAclModuleLog(null,sysAclModule);

    }

    /**
     * 更新操作
     *
     * @param param
     */
    public void update(AclModuleParam param) {
        BeanValidatorUtil.check(param);
        if (checkExist(param.getParentId(), param.getName(), param.getId())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的部门不存在");
        //递归获取所有子模块的id 封装成一个集合
        List<Integer> subIdList =Lists.newArrayList();
        getSubIdList(param.getId(),subIdList);

        //如果param.getparentId 在子模块的id集合里 就抛出异常
        if(subIdList.contains(param.getParentId())){
            throw new ParamException("上级模块不能为当前模块的子模块");
        }


        SysAclModule after = SysAclModule.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        after.setLevel(LevelUtil.getLevel(getLevel(param.getParentId()), param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        updateWithChild(before, after);
        iSysLogService.saveAclModuleLog(before,after);
    }

    /**
     * 更新-子节点更新
     *
     * @param before
     * @param after
     */
    @Transactional
    private void updateWithChild(SysAclModule before, SysAclModule after) {
        String oldLevelPrefix = before.getLevel();
        String newLevelPrefix = after.getLevel();
        if (!StringUtils.equals(oldLevelPrefix, newLevelPrefix)) {
            List<SysAclModule> aclModuleList = sysAclModuleMapper.getChildAclModuleListByLevel(before.getLevel() + "." + before.getId());
            if (CollectionUtils.isNotEmpty(aclModuleList)) {
                for (SysAclModule aclModule : aclModuleList) {
                    String level = aclModule.getLevel();
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        aclModule.setLevel(level);
                    }
                }
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKeySelective(after);

    }

    /**
     * 删除操作
     *
     * @param id
     */
    public void delete(int id) {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(id);
        Preconditions.checkNotNull(aclModule, "要删除的权限模块不存在，无法删除");
        if (sysAclModuleMapper.countByParentId(aclModule.getId()) > 0) {
            throw new ParamException("当前权限模块下有子模块,无法删除");
        }
        if(sysAclMapper.countByAclModuleId(aclModule.getId())>0){
            throw new ParamException("当前权限模块下有权限，无法删除");
        }
        sysAclModuleMapper.deleteByPrimaryKey(id);
        iSysLogService.saveAclModuleLog(aclModule,null);

    }


    /**
     * 检查同一层级下是否有相同名称的模块
     *
     * @param parentId
     * @param aclModuleName
     * @param aclModuleId
     * @return
     */
    private boolean checkExist(Integer parentId, String aclModuleName, Integer aclModuleId) {
        return sysAclModuleMapper.countByNameAndParentIdAndId(parentId, aclModuleName, aclModuleId) > 0;
    }


    /**
     * 获取部门所在层级level
     *
     * @param aclModuleId
     * @return
     */
    private String getLevel(Integer aclModuleId) {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (aclModule == null) {
            return null;
        }
        return aclModule.getLevel();
    }

    /**
     * 递归获得当前选择模块的子模块的id集合
     * @param parentId
     * @param subIdList
     */
    private void getSubIdList(Integer parentId,List<Integer> subIdList) {
        List<SysAclModule> sysAclModuleList = sysAclModuleMapper.selectByParentId(parentId);
        if (CollectionUtils.isNotEmpty(sysAclModuleList)) {
            for (SysAclModule sysAclModule : sysAclModuleList) {
                subIdList.add(sysAclModule.getId());
                getSubIdList(sysAclModule.getId(),subIdList);
            }
        }
    }


}
